<?php

class Admin_PublicacaosimuladoController extends App_Controller_Action
{

    private $_table     = 'PUBLICACAO_SIMULADO';
    private $_pk        = 'PLS_ID';
    private $_order_col = 'PLS_DAT DESC, PLS_HOR DESC, PLS_ID';
    private $_order     = 'DESC';
    private $_sta_col   = 'PLS_STA';
    private $obj        = '';
    private $form       = '';
    
    private $_PER_ID;
    private $_USU_ID;
    
    public function init()
    {
        if($this->getRequest()->getActionName() == 'edit') $this->form = new Admin_Form_Publicacaosimulado();
        
        $auth = Zend_Auth::getInstance();
        $s_user = $auth->getStorage();
        $this->_PER_ID = $s_user->read()->PER_ID;
        $this->_USU_ID = $s_user->read()->USU_ID;
    }
 
    public function indexAction() {
        
        Zend_Loader::loadClass('datetools','library');
        Zend_Loader::loadClass('elemform','library');
        Zend_Loader::loadClass('dominio','library');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/validation/dist/jquery.validate.min.js');
         
        $where = $this->_pk . ' > 0';
        
        
        $stafiltro = $this->_getParam('stafiltro', '1,2');      
        if($stafiltro != '') $where .= ' and PLS_STA in(' . $stafiltro.')';    
        $this->view->stafiltro = $stafiltro;
        
        //if($this->_PER_ID <> 1) $where .= ' AND USU_ID = '.$this->_USU_ID;
        
        $query = 'SELECT SQL_CACHE * FROM '.$this->_table.' WHERE '.$where.' ORDER BY '.$this->_order_col.' '.$this->_order;
        $result = $this->db->fetchAll($query);
        $this->view->result = $this->paginacao($result);
        
    }
    
    public function editAction() {
        
        Zend_Loader::loadClass('tools','library');
        Zend_Loader::loadClass('datetools','library');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskMoney.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskedinput.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/mask.js');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/validation/dist/jquery.validate.min.js');
        
        $this->view->headLink()->prependStylesheet($this->_urlbase.'/public/media/js/chosen/chosen.min.css'); 
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/chosen/chosen.jquery.min.js');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_publicacaolista.js');
        
        
        $this->view->form = $this->form;
        if($this->getRequest()->isPost()) { 
            $formData = $this->getRequest()->getPost();
            try {
                if($this->form->isValid($formData)) {
                    $id = (int) $this->form->getValue($this->_pk);
                    
                    $data = $formData;//$this->form->getValues(); 
                    
                    unset($data['Salvar']);
                    unset($data['destino']);
                    
                    $this->db->beginTransaction();
                    if($id == 0){ 
                        
                        $query = 'SELECT SQL_CACHE * FROM LISTA_SIMULADO WHERE LTS_ID = '.$data['LTS_ID'];
                        $row = $this->db->fetchRow($query);
                        
                        $ALU_ID = isset($data['ALU_ID']) ? implode(',', $data['ALU_ID']):'';
                        $CBS_ID = isset($data['CBS_ID']) ? implode(',', $data['CBS_ID']):'';
                        $CUR_ID = isset($data['CUR_ID']) ? implode(',', $data['CUR_ID']):'';
                        
                        $arr = array(
                            'LTS_ID'  => $row['LTS_ID'],
                            'PLS_NOM' => $row['LTS_NOM'],
                            'PLS_DSC' => $row['LTS_DSC'],
                            //'PLS_DATENC' => Datetools::dma_amd($data['PLS_DATENC']),
                            //'PLS_HORENC' => $data['PLS_HORENC'],
                            'PLS_DAT' => date('Y-m-d'),
                            'PLS_HOR' => date('H:i:00'),
                            'PLS_ANO' => date('Y'),
                            'USU_ID'  => $this->_USU_ID, 
                            'ALU_ID'  => $ALU_ID,
                            'CBS_ID'  => $CBS_ID,
                            'CUR_ID'  => $CUR_ID,
                            'PLS_STA' => '1',
                            'PLS_REDID' => $row['LTS_REDID'],
                            'PLS_REDNQU' => $row['LTS_REDNQU'],
                            'PLS_REDPES' => $row['LTS_REDPES'],
                        );
                        $this->db->insert($this->_table,$arr);
                        $id = $this->db->lastInsertId(); 
                        
                        // cria gabarito
                        $query = 'SELECT SQL_CACHE * FROM LISTA_SIMULADO_GABARITO WHERE LTS_ID = '.$data['LTS_ID'];
                        $rows = $this->db->fetchAll($query);
                        foreach($rows as $row){
                            $arr = array(
                                'PLS_ID'  => $id,
                                'PSG_QST' => $row['LSG_QST'],
                                'PSG_ALT' => $row['LSG_ALT'],
                                'DCP_ID'  => $row['DCP_ID'],
                                'PSG_TPO' => $row['LSG_TPO'],
                                'PSG_STALNGETG' => $row['LSG_STALNGETG'],
                                'PSG_PES' => $row['LSG_PES'],
                            );
                            $this->db->insert('PUBLICACAO_SIMULADO_GABARITO',$arr);
                        }
                        
                        
                        if($data['LTS_ID'] > 0){
                            
                            //alunos
                            if($formData['destino'] == 'a'){
                                foreach($data['ALU_ID'] as $aluno){

                                    $arr2 = array(
                                        'PLS_ID'  => $id,
                                        'ALU_ID'  => $aluno,  
                                    );
    
                                    if($this->validaPubAluno($id,$aluno))
                                        $this->db->insert('PUBLICACAO_SIMULADO_ALUNO',$arr2);
                                    
                                }
                            // cursos
                            } else if($formData['destino'] == 'c'){
                                foreach($data['CBS_ID'] as $curso){    

                                    $query = 'SELECT SQL_CACHE DISTINCT m.ALU_ID '
                                            .' FROM MATRICULA m, CURSO c, CURSOBASE cb '
                                            .' WHERE m.CUR_ID = c.CUR_ID AND cb.CBS_ID = c.CBS_ID '
                                            .' AND m.MAT_STA = 1 AND c.CUR_STA = 1 AND cb.CBS_ID = '.$curso.'';
                                    $result = $this->db->fetchAll($query);

                                    foreach($result as $alu){

                                        $arr2 = array(
                                            'PLS_ID'  => $id,
                                            'ALU_ID'  => $alu['ALU_ID'],
                                        );
                                        
                                        if($this->validaPubAluno($id,$alu['ALU_ID']))
                                            $this->db->insert('PUBLICACAO_SIMULADO_ALUNO',$arr2);
                                    }
                                }
                            //grupos
                            } else if($formData['destino'] == 'g'){
                                foreach($data['CUR_ID'] as $grupo){    

                                    $query = 'SELECT SQL_CACHE DISTINCT m.ALU_ID '
                                            .' FROM MATRICULA m, CURSO c '
                                            .' WHERE m.CUR_ID = c.CUR_ID '
                                            .' AND m.MAT_STA = 1 AND c.CUR_STA = 1 AND c.CUR_ID = '.$grupo.'';
                                    $result = $this->db->fetchAll($query);

                                    foreach($result as $alu){

                                        $arr2 = array(
                                            'PLS_ID'  => $id,
                                            'ALU_ID'  => $alu['ALU_ID'],
                                        );
                                        
                                        if($this->validaPubAluno($id,$alu['ALU_ID']))
                                            $this->db->insert('PUBLICACAO_SIMULADO_ALUNO',$arr2);
                                    }

                                }
                            }
                        }
                    }
                    else{
                        $arr = array(
                            'PLS_STA' => $data['PLS_STA'],
                        );
                        
                        $this->db->update($this->_table,$arr, $this->_pk.' = ' . $id);
                    }
                    
                    $this->db->commit();
                    
                    $this->_helper->redirector('index');
                } else {
                    $this->form->populate($formData);
                }
            } catch(Exception $ex) {
                echo '<script> alert("'.$ex->getMessage().'");</script>';
                $this->form->populate($formData);
                $this->db->rollBack();
            }
        } else {
            $id = $this->_getParam('id', 0);
            if ($id > 0) {
                $query = 'SELECT SQL_CACHE * FROM '.$this->_table.' WHERE '.$this->_pk . ' = ' . $id;
                $data = $this->db->fetchRow($query);
                //$data['PLS_DATENC'] = Datetools::amd_dma($data['PLS_DATENC']);
                $this->form->populate($data);
                $this->view->data = $data;
            }
        }
    }

    public function deleteAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = FALSE;
        $msg = '';
        $id = $this->_getParam('id', 0);
        if((int) $id > 0 ) {   
            $this->db->beginTransaction();
            try {
                
                $ok = (bool) $this->db->delete('PUBLICACAO_SIMULADO_RESPOSTA', $this->_pk . ' = ' . $id);
                $ok = (bool) $this->db->delete('PUBLICACAO_SIMULADO_ALUNO', $this->_pk . ' = ' . $id);
                $ok = (bool) $this->db->delete('PUBLICACAO_SIMULADO_GABARITO', $this->_pk . ' = ' . $id);
                $ok = (bool) $this->db->delete($this->_table, $this->_pk . ' = ' . $id);
                
                $this->db->commit();
            } catch(Exception $ex) {
                //echo getMessage();
                $ok = FALSE;
                $msg = MSG_DELETE;
                $this->db->rollBack();
            }             
        }       
        echo json_encode(array('ok' => $ok, 'msg'=> $msg));
        //$this->_helper->redirector('index');
    }
    
    public function validaPubAluno($id,$aluno) {
        
        $query = 'SELECT SQL_CACHE ALU_ID FROM PUBLICACAO_SIMULADO_ALUNO WHERE PLS_ID = '.$id.' AND ALU_ID = '.$aluno;
        $row = $this->db->fetchRow($query);
        if($row['ALU_ID'] > 0 ) return false;
        else return true;
        
    }
   
}